package rwlivbk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import rwlivbk.Service.RedisService;
import rwlivbk.common.CommonResult;
import rwlivbk.mapper.DishMapper;
import rwlivbk.model.Dish;

import java.util.ArrayList;


@RestController
@CrossOrigin
@RequestMapping("/admin-api/dishes")
public class DishesController {

    private final DishMapper dishMapper;
    private final RedisService redisService; // Assuming you have a Redis service

    @Autowired
    public DishesController(DishMapper dishMapper, RedisService redisService) {
        this.dishMapper = dishMapper;
        this.redisService = redisService;
    }

    @GetMapping("/getTodayDishes")
    public CommonResult<?> getTodayDishes() {
        // Try to get today's dishes from Redis
        ArrayList<Dish> dishes = redisService.getTodayDishes();
        if (dishes == null) {
            // If not found in Redis, get from MySQL
            dishes = dishMapper.findAllTodayDishes();
            // Store in Redis for future requests
            redisService.setTodayDishes(dishes);
        }
        return CommonResult.success(dishes);
    }

    @GetMapping("/getAllDishes")
    public CommonResult<?> getAllDishes() {

        ArrayList<Dish> dishes = dishMapper.findAllDishes();
        return CommonResult.success(dishes);
    }

    @GetMapping("/getAllDishesEvenDeleted")
    public CommonResult<?> getAllDishesEvenDeleted() {

        ArrayList<Dish> dishes = dishMapper.findAllDishesEvenDeleted();
        return CommonResult.success(dishes);
    }

    @GetMapping("/getDeletedDishes")
    public CommonResult<?> getDeletedDishes() {

        ArrayList<Dish> dishes = dishMapper.findAllDeletedDishes();
        return CommonResult.success(dishes);
    }

    @PostMapping("/add")
    public CommonResult<?> addDish(@RequestBody Dish dish) {
        dishMapper.insertDish(dish);
        redisService.deleteTodayDishesCache(); // Delete the cache
        return CommonResult.success(200);
    }

    @PutMapping("/update")
    public CommonResult<?> updateDish(@RequestBody Dish dish) {
        dishMapper.updateDish(dish);
        redisService.deleteTodayDishesCache(); // Delete the cache
        return CommonResult.success(200);
    }

    @DeleteMapping("/delete/{dish_id}")
    public CommonResult<?> deleteDish(@PathVariable Integer dish_id) {
        dishMapper.deleteDish(dish_id);
        redisService.deleteTodayDishesCache(); // Delete the cache
        return CommonResult.success(200);
    }
}
